package com.coding.basic.stack.expr;

import java.util.List;
import java.util.Stack;

public class PrefixExpr {
    String expr = null;

    public PrefixExpr(String expr) {
        this.expr = expr;
    }

    public float evaluate() {
        if (expr == null) {
            throw new NullPointerException("expr can't be null");
        }
        TokenParser tokenParser = new TokenParser();
        List<Token> tokenList = tokenParser.parse(expr);

        Stack<Token> tokenStack = new Stack<>();
        for (Token token : tokenList) {
            tokenStack.push(token);
        }

        Stack<Float> numStack = new Stack<>();
        while (!tokenStack.isEmpty()) {
            Token token = tokenStack.pop();
            if (token.isOperator()) {
                String operator = token.toString();
                float f1 = numStack.pop();
                float f2 = numStack.pop();

                numStack.push(calculate(operator, f1, f2));
            } else if (token.isNumber()) {
                numStack.push((float) token.getIntValue());
            }
        }

        return numStack.pop();
    }

    private Float calculate(String op, Float f1, Float f2) {
        if (op.equals("+")) {
            return f1 + f2;
        }
        if (op.equals("-")) {
            return f1 - f2;
        }
        if (op.equals("*")) {
            return f1 * f2;
        }
        if (op.equals("/")) {
            return f1 / f2;
        }
        throw new RuntimeException(op + " is not supported");
    }

}